package com.jtfr.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.LinkedBlockingDeque;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 连接管理 ：用一个LinkedBlockingDeque操作
 * @author ckm
 *
 */
public class ConnectionManager {
	
	private static Logger LOGGER = LoggerFactory.getLogger(ConnectionManager.class);
	// 创建 连接池存放对象 多少个连接就开辟多大的初始空间
	private static LinkedBlockingDeque<Connection> connectionPool = new LinkedBlockingDeque<Connection>(Config.getConfig().getConnectionPoolSize());
	
	static {
		// 初始化连接池，填入8个连接
		for (int i = 0; i < Config.getConfig().getConnectionPoolSize(); i++) {
			Connection connection = null;
			try {
				// 创建连接对象 url username password
				connection = DriverManager.getConnection(Config.getConfig().getUrl(), Config.getConfig().getUsername(), Config.getConfig().getPassword());
			} catch (SQLException e) {
				LOGGER.error("创建连接失败", e);
				throw new RuntimeException("创建连接失败", e);
			}
			connectionPool.push(connection);
		}	
	}
	
	/**
	 * 获取连接, 阻塞获取的方式
	 * @return
	 */
    public static Connection get() {
    	Connection connection = null;
        try {
        	connection = connectionPool.takeFirst();
		} catch (InterruptedException e) {
			LOGGER.error("获取连接池失败", e);
			throw new RuntimeException("获取连接池失败", e);
		}
        return connection;
    }
    
    /**
     * 使用完后再存入
     */
    public static void set(Connection connection) {
    	connectionPool.push(connection);
    }
}
